<?php
namespace Api\Controller;
use Think\Controller;
use Com\Aliyun\api_sdk\lib\Core\Config;
use Com\Aliyun\api_sdk\lib\Core\Regions\EndpointConfig;
use Com\Aliyun\api_sdk\lib\Core\Profile\DefaultProfile;
use Com\Aliyun\api_sdk\lib\Core\DefaultAcsClient;
use Com\Aliyun\api_sdk\lib\Api\Sms\Request\V20170525\SendSmsRequest;
use Com\Aliyun\api_sdk\lib\Api\Sms\Request\V20170525\QuerySendDetailsRequest;
class UserController extends BaseController{
  /**
  *get
  *@param: 
  *@return:
  */
  public function sendSmsToken(){
    $phone = I('get.phone');
    if(!$phone){
      $this->response(array('info'=>'请输入手机号！'),json,400);
    }
    $length = 6;
    $token = rand(pow(10,($length-1)), pow(10,$length)-1);
    cookie('token',$token,600);//10分钟有效
    $response = $this->sendSms(
      "四方当代美术馆",
      "SMS_105240052",
      $phone,
      Array(
        "code"=>$token
      )
    );
    $this->response(array('info'=>'success'),json,200);
  }

  /**
  *发送订票成功信息
  *@param: 
  *@return:
  */
  public function sendOrderSuccess($phone,$exhibition_name,$ticket_name,$number,$code){
    $response = $this->sendSms(
      "四方当代美术馆",
      "SMS_108950007",
      $phone,
      Array(
        "content"=>$exhibition_name.$ticket_name.$number,
        "code"=>$code
      )
    );
    return ;
  }

  static $acsClient = null;

  /**
   * 取得AcsClient
   *
   * @return DefaultAcsClient
   */
  public static function getAcsClient() {
      //产品名称:云通信流量服务API产品,开发者无需替换
      $product = "Dysmsapi";

      //产品域名,开发者无需替换
      $domain = "dysmsapi.aliyuncs.com";

      // TODO 此处需要替换成开发者自己的AK (https://ak-console.aliyun.com/)
      $accessKeyId = "LTAIooaqNcG0H3nL"; // AccessKeyId

      $accessKeySecret = "srb2twPV4IJlMvVFfPkxgjgBVuJq6D"; // AccessKeySecret


      // 暂时不支持多Region
      $region = "cn-hangzhou";

      // 服务结点
      $endPointName = "cn-hangzhou";


      if(static::$acsClient == null) {

          //初始化acsClient,暂不支持region化
          $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
          // 手动加载endpoint
          EndpointConfig::load();
          // 增加服务结点
          DefaultProfile::addEndpoint($endPointName, $region, $product, $domain);

          // 初始化AcsClient用于发起请求
          static::$acsClient = new DefaultAcsClient($profile);
      }
      return static::$acsClient;
  }

  /**
   * 发送短信
   *
   * @param string $signName <p>
   * 必填, 短信签名，应严格"签名名称"填写，参考：<a href="https://dysms.console.aliyun.com/dysms.htm#/sign">短信签名页</a>
   * </p>
   * @param string $templateCode <p>
   * 必填, 短信模板Code，应严格按"模板CODE"填写, 参考：<a href="https://dysms.console.aliyun.com/dysms.htm#/template">短信模板页</a>
   * (e.g. SMS_0001)
   * </p>
   * @param string $phoneNumbers 必填, 短信接收号码 (e.g. 12345678901)
   * @param array|null $templateParam <p>
   * 选填, 假如模板中存在变量需要替换则为必填项 (e.g. Array("code"=>"12345", "product"=>"阿里通信"))
   * </p>
   * @param string|null $outId [optional] 选填, 发送短信流水号 (e.g. 1234)
   * @return stdClass
   */
  public static function sendSms($signName, $templateCode, $phoneNumbers, $templateParam = null, $outId = null) {

      // 初始化SendSmsRequest实例用于设置发送短信的参数
      $request = new SendSmsRequest();

      // 必填，设置雉短信接收号码
      $request->setPhoneNumbers($phoneNumbers);

      // 必填，设置签名名称
      $request->setSignName($signName);

      // 必填，设置模板CODE
      $request->setTemplateCode($templateCode);

      // 可选，设置模板参数
      if($templateParam) {
          $request->setTemplateParam(json_encode($templateParam));
      }

      // 可选，设置流水号
      if($outId) {
          $request->setOutId($outId);
      }

      // 发起访问请求
      $acsResponse = static::getAcsClient()->getAcsResponse($request);

      // 打印请求结果
      // var_dump($acsResponse);

      return $acsResponse;

  }

  /**
  *检测是否注册个人信息
  *@param: 
  *@return:
  */
  public function userTest(){
    // $user = session('visitor_id');
    $user = cookie('visitor_id');
    if($user){
      $this->response(array('info'=>true),json,200);
    }else{
      $this->response(array('info'=>false),json,200);
    }
    
  }

  /**
  *注册/登陆 post
  *@param: redeem_code
  *@return:
  */
  public function register(){
    // $uid = $this->securityTest();
    $post = json_decode(file_get_contents('php://input'), true);
    // $post = I('post.');
    if(!$post['phone']){
      $this->response(array('info'=>'请输入手机号！'),json,400);
    }
    if(!$post['token']){
      $this->response(array('info'=>'请输入验证码！'),json,400);
    }
    $sys_token = cookie('token');
    if($post['token']!=$sys_token){
      $this->response(array('info'=>'验证码错误或已超过10分钟有效期，请重新获取'),json,400);
    }
    
    $re_user = M('visitor')->where(array('phone'=>$post['phone']))->find();
    if($re_user){
      // session('visitor_id',$re_visitor['id'],3600);
      cookie('visitor_id',$re_user['id'],30*24*3600);
    }else{
      // $wechat_info = session('wechat_info');
      // $post['openid'] = $wechat_info['openid'];
      // $post['nickname'] = $wechat_info['nickname'];
      // $post['name'] = $wechat_info['nickname'];
      $post['reg_time'] = time();
      $re_visitor = M('visitor')->add($post);
      // session('visitor_id',$re_user,3600);
      cookie('visitor_id',$re_visitor,30*24*3600);
    }

    $this->response(array('info'=>'success'),json,200);
  }

  /**
  *获取我的订单
  *@param: 
  *@return:
  */
  public function getProductOrders(){
    $uid = $this->securityTest();
    $orders = M('product_order')
    ->where(array('visitor_id'=>$uid))
    ->order('create_time desc')
    ->select();
    foreach ($orders as $order_key => $order) {
      # code...
      if(strlen($order['cart_ids'])>0){
        $ids = explode(',',$order['cart_ids']);
        $products = array();
        foreach ($ids as $key => $value) {
          $product = M('cart')
          ->field('cart.*,picture.path as product_cover,product.name as product_name,product.name_en as product_name_en,product_attribution.name as attr_name')
          ->where(array('cart.id'=>$value))
          ->join('product on product.id = cart.product_id')
          ->join('product_attribution on product_attribution.id = cart.attribution_id')
          ->join('picture on picture.id = product.cover','left')
          ->find();
          array_push($products,$product);
        }
        $orders[$order_key]['products'] = $products;
      }
    }
    $this->response(array('info'=>$orders),json,200);
  }

  /**
  *获取我的门票
  *@param: 
  *@return:
  */
  public function getTicketRedeemCodes(){
    $uid = $this->securityTest();
    $orders = M('ticket_order')
    ->field('ticket_order.*,ticket.name as ticket_name,ticket.name_en as ticket_name_en,exhibition.name as exhibition_name,exhibition.name_en as exhibition_name_en,exhibition.type as exhibition_type,picture.path as exhibition_cover_path,payment.price as total_price')
    ->where(array('ticket_order.visitor_id'=>$uid))
    ->where('ticket_order.status = 1 or ticket_order.status = 4')
    ->join('ticket on ticket.id = ticket_order.ticket_id','left')
    ->join('exhibition on exhibition.id = ticket.exhibition_id','left')
    ->join('picture on picture.id = exhibition.cover','left')
    ->join('payment on payment.id = ticket_order.payment_num','left')
    ->order('create_time desc')
    ->select();
    foreach ($orders as $key => $value) {
      # code...
      $orders[$key]['codes'] = M('ticket_redeem_code')
      ->where(array('ticket_order_id'=>$value['id']))
      ->order('create_time desc')
      ->select();
    }
    $this->response(array('info'=>$orders),json,200);
  }

  /**
  *个人信息
  *@param: 
  *@return:
  */
  public function profile(){
    $uid = $this->securityTest();
    $user = M('visitor')->find($uid);
    $vip_check=M('vip_order')
    ->where(array('visitor_id'=>$uid))
    ->join('membership on membership.id = vip_order.vip_type','left')
    ->field('vip_order.*,membership.title as vip_title,membership.title_en as vip_title_en')
    ->order('end_time desc')
    ->find();
    $identity='普通会员';
    $identity_en='Consumer';
    if($vip_check&&$vip_check['end_time']>time()){
      $identity=$vip_check['vip_title'];
      $identity_en=$vip_check['vip_title_en'];
    }
    $user['vip_title'] = $identity;
    $user['vip_title_en'] = $identity_en;
    $user['vip_start_time'] = $vip_check['start_time']?$vip_check['start_time']:null;
    $user['vip_end_time'] = $vip_check['end_time']?$vip_check['end_time']:null;
    $this->response(array('info'=>$user),json,200);
  }

  /**
  *个人信息
  *@param: 
  *@return:
  */
  public function gotoMyticket(){
    $uid = $this->securityTest();
    redirect(__ROOT__."/Public/museum/www/#/my_ticket");
  }

  /**
  *修改个人信息
  *@param: 
  *@return:
  */
  public function editProfile(){
    $uid = $this->securityTest();
    $post = json_decode(file_get_contents('php://input'), true);
    $user = M('visitor')->where(array('id'=>$uid))->save($post);
    $this->response(array('info'=>'保存成功'),json,200);
  }

  /**
  *添加name
  *@param: 
  *@return:
  */
  public function profileNmae(){
    $users = M('visitor')->select();
    foreach ($users as $key => $value) {
      # code...
      if($value['nickname']&&!$value['name']){
        M('visitor')->where(array('id'=>$value['id']))->save(array('name'=>$value['nickname']));
      }
    }
  }

  /**
  *退出登录
  *@param: 
  *@return:
  */
  public function logout(){
    cookie('visitor_id',null);
    $this->response(array('info'=>'已退出'),json,200);
  }

}